package com.sky.sentinel.nacos.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SentinelConfig {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    /**
     * 指定修改流控规则：FlowRuleManager
     * @param rule
     */
    public static void initFlowQpsRule(String rule){
        if (StringUtils.isNotBlank(rule)) {
            JSONObject json = JSONObject.parseObject(rule);
            List<FlowRule> rules = new ArrayList<>();
            FlowRule rule1 = new FlowRule();
            rule1.setResource(json.getString("resource"));
            // set limit qps to 20
            rule1.setCount(json.getInteger("count"));
            // RuleConstant
            rule1.setGrade(json.getInteger("grade"));
            rule1.setLimitApp("default");
            rules.add(rule1);
            FlowRuleManager.loadRules(rules);
        }
    }

    /**
     * 指定修改降级规则：FlowRuleManager
     * @param rule
     */
    public static void initDegradeRule(String rule){
        if (StringUtils.isNotBlank(rule)) {
            JSONObject json = JSONObject.parseObject(rule);
            List<DegradeRule> rules = new ArrayList<>();
            DegradeRule rule1 = new DegradeRule();
            rule1.setResource(json.getString("resource"));
            // set limit qps to 20
            rule1.setCount(json.getInteger("count"));
            // RuleConstant
            rule1.setGrade(json.getInteger("grade"));
            rule1.setLimitApp("default");
            rules.add(rule1);
            DegradeRuleManager.loadRules(rules);
        }
    }
}
